<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="450px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="组件物料" prop="materialId">
          <select-content-input
            v-if="!props.isReadonly"
            title="组件物料"
            :width="300"
            :isMultiple="false"
            :showSelectDevice="formData.materialList"
            :plantId="propsPlantId"
            @get-device="(id, object) => getDevice(id, object)"
          />
          <span v-else>{{
            formData.materialName + "-" + formData.materialCode
          }}</span>
        </el-form-item>
        <el-form-item label="数量" prop="matQuantity">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.matQuantity"
            placeholder="请输入数量"
            clearable
            style="width: 300px"
          />

          <span v-else>{{ formData.matQuantity }}</span>
        </el-form-item>
        <el-form-item label="数量单位" prop="quantityUnit">
          <el-select
            v-model="formData.quantityUnit"
            placeholder="请选择数量单位"
            clearable
            disabled
            style="width: 300px"
          >
            <el-option
              v-for="item in useDictionary('MeasurementUnit')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否是虚拟件" prop="virtualParts">
          <el-radio-group v-model="formData.virtualParts">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            clearable
            style="width: 300px"
          />

          <text v-else>{{ formData.remarks }}</text>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
defineOptions({
  name: "MESMESBOMDETAILADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  addData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  plantId: {
    type: String,
    default: () => {
      return "";
    },
  },
  parentId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    formData.parentId = props.parentId;
  }
);
const propsPlantId = ref("");
watch(
  () => props.plantId,
  (newVal: string) => {
    propsPlantId.value = newVal;
  }
);

watch(
  () => props.addData,
  (newVal: object) => {
    const { bomCode, plantId, plantCode } = newVal;
    Object.assign(formData, {
      bomCode,
      plantId,
      plantCode,
    });

    formData.bomId = newVal.id;
    console.log(newVal, "newVal");
    if (!formData.parentId) {
      formData.parentId = "0";
    }
  }
);

watch(
  () => props.parentId,
  (newVal: string) => {
    formData.parentId = newVal;
  }
);
const rules = reactive({
  materialId: [
    { required: true, message: "请输入组件物料", trigger: "change" },
  ],
  matQuantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  quantityUnit: [
    { required: true, message: "请选择数量单位", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  bomId: "",
  bomCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  virtualParts: 0,
  matQuantity: "",
  quantityUnit: "",
  version: "",
  remarks: "",
  parentId: "",
  allId: "",
  allCode: "",
  allName: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  materialList: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        bomId,
        bomCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        virtualParts,
        matQuantity,
        quantityUnit,
        version,
        remarks,
        parentId,
        allId,
        allCode,
        allName,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        bomId,
        bomCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        virtualParts,
        matQuantity,
        quantityUnit,
        version,
        remarks,
        parentId,
        allId,
        allCode,
        allName,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      formData.materialList = [
        {
          id: newVal.materialId,
          materialName: newVal.materialName,
          materialCode: newVal.materialCode,
          unit: newVal.quantityUnit,
        },
      ];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  // formRef.value.clearValidate();
  formData.id = "";
  formData.bomId = "";
  formData.bomCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.virtualParts = 0;
  formData.matQuantity = "";
  formData.quantityUnit = "";
  formData.version = "";
  formData.remarks = "";
  formData.parentId = "";
  formData.allId = "";
  formData.allCode = "";
  formData.allName = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ];
}

const loading = ref(false);

/** BOM明细保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesbomdetail/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 提示：该组件放到了mes/mesbom/content/components下
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any, index: number) {
  formData.materialId = Objects[0].id;
  formData.materialCode = Objects[0].materialCode;
  formData.materialName = Objects[0].materialName;
  formData.quantityUnit = Objects[0].unit;
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
